package org.xiaov.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.thymeleaf.TemplateEngine;
import org.xiaov.core.bean.BeanHelper;

import javax.annotation.Resource;

/**
 * <p>
 *
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/3/4 20:47
 */
@SpringBootConfiguration
public class EmailConfig {

    @Resource
    private MailProperties mailProperties;

    private static final String DEFAULT_HOST = "127.0.0.1";
    private static final String DEFAULT_USERNAME = "ROOT";
    private static final String DEFAULT_PWD = "ROOT";
    private static final Integer DEFAULT_PORT = 25;
    private static final String DEFAULT_PROTOCOL = "smtp";
    private static final String DEFAULT_ENCODING = "UTF-8";

    @Bean
    @ConditionalOnMissingBean
    public MailProperties mailProperties() {
        return new MailProperties();
    }


    /**
     * 默认的mail的配置
     *
     * @return JavaMailSender
     */
    @Bean
    @ConditionalOnMissingBean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        String host = BeanHelper.val(mailProperties.getHost(), DEFAULT_HOST);
        javaMailSender.setHost(host);
        String username = BeanHelper.val(mailProperties.getUsername(), DEFAULT_USERNAME);
        javaMailSender.setUsername(username);
        String pwd = BeanHelper.val(mailProperties.getPassword(), DEFAULT_PWD);
        javaMailSender.setPassword(pwd);
        Integer port = BeanHelper.val(mailProperties.getPort(), DEFAULT_PORT);
        javaMailSender.setPort(port);
        String protocol = BeanHelper.val(mailProperties.getProtocol(), DEFAULT_PROTOCOL);
        javaMailSender.setProtocol(protocol);
        String encoding = BeanHelper.val(mailProperties.getDefaultEncoding().toString(), DEFAULT_ENCODING);
        javaMailSender.setDefaultEncoding(encoding);
        return javaMailSender;
    }

    /**
     * 配置TemplateEngine
     *
     * @return TemplateEngine对象
     */
    @Bean
    @ConditionalOnMissingBean
    public TemplateEngine templateEngine() {
        return new TemplateEngine();
    }

}
